Skip to content

fix(harness): preserve subscriber context in async tool execution - #3299

Open
breezeFur wants to merge 4 commits into
agentscope-ai:mainfrom
breezeFur:fix/2681-async-tool-reactor-context
Open

breezeFur wants to merge 4 commits into
agentscope-ai:mainfrom
breezeFur:fix/2681-async-tool-reactor-context

Conversation

@breezeFur

@breezeFur breezeFur commented Sep 26, 2026 •

Copy link
Copy Markdown

AgentScope-Java Version

2.1.0-SNAPSHOT, synchronized with main at 9cfeaad4b.

Description

Related to #2681 — only the remaining Reactor Context propagation gap, not a claim to resolve every post-timeout event-routing concern in that issue.

AsyncToolMiddleware invokes next.apply(input).subscribe(...) inside Flux.create. That detached subscription does not inherit the caller's Reactor subscriber Context. This PR captures the subscriber context once at the subscription boundary and forwards it to detached tool execution and background operations with contextWrite.

Current main already recovers an AgentEventEmitter in ReActAgent's tool execution path, and the existing child-event integration test passes with that workaround. This patch fixes the earlier middleware boundary itself, including arbitrary caller context entries and forwarding-emitter identity; it does not remove or change the existing recovery.

Changes

  • Propagate the subscriber Context into the detached tool execution, per subscription.
  • Forward the same captured Context through asyncToolRegistry.register/complete/fail, messageBus.inboxPush, and messageBus.enqueueWakeup.
  • Preserve the existing offload, cancellation, inbox, completion-callback, and subagent wakeup behavior.
  • Add a DEBUG diagnostic using the existing SLF4J logger (session and context key count only; no context values).
  • Add deterministic regression coverage for independent subscriptions, emitter/forwarding-emitter identity, caller request context, the detached error channel, and continued context access after foreground offload completes.

Merge conflict resolution

The branch was synchronized with main after #4530 changed the same middleware. Merge commit 185e4ac1eb5c440f5b7bf69eb5b58ecac3cf5f12 combines both contracts:

  • the PR's Context forwarding remains on all asynchronous registry/message-bus subscriptions;
  • upstream's SUPPRESS_COMPLETION_CALLBACK, quiet-completion handling, and isSubagentCall behavior remain intact.

The PR diff against current main is still limited to AsyncToolMiddleware.java and its test.

Reproduction and validation

Environment: Windows, Microsoft JDK 21.0.10, Maven 3.9.6; repository Java release remains 17. No model service, Docker, database, or cloud credentials are needed.

Red: applying only the first regression to unmodified production code runs 1 test and fails with NoSuchElementException at AgentEventEmitter.fromContext(context).orElseThrow(). It is not a build/dependency failure or a zero-test run.

For merge head 185e4ac1e:

  • related harness/core regression suite: 197 tests, 0 failures, 0 errors, 0 skipped;
  • spotless:apply, reactor spotless:check, and git diff --check: passed;
  • GitHub CI run 46784999432: Ubuntu build (16m18s), Windows build (13m58s), Check License, Check Module Sync, and license/cla all passed;
  • GitHub now reports mergeable=MERGEABLE and mergeStateStatus=CLEAN.

Scope / review status

  • No API, dependency, permission-policy, or storage-format changes.
  • Post-timeout direct emitter delivery / event-routing semantics are deliberately unchanged; this PR does not close [Bug]:agentscope.agent.event.emitter 和 AsyncToolMiddleware #2681 automatically.
  • AI-assisted diagnosis and implementation. Commands and test results above were actually executed locally or are linked GitHub check runs.
  • All six review threads are resolved, with no unresolved review threads on the latest head.
  • oss-maintainer approved ca6b5913 before this merge commit. The code diff is unchanged by the synchronization, but the latest merge head still benefits from maintainer re-confirmation.
  • The approval is a code-level automated review signal and does not establish independent human or account-owner sign-off.
  • The contributor account has read-only access to the upstream repository. Squash merge and final approval remain maintainer actions.

Checklist

  • Changed Java files formatted with Spotless; reactor Spotless checks pass
  • Related regression tests pass on merge head (197)
  • Full repository test suite (not run locally; full Ubuntu/Windows CI passed)
  • All review threads resolved
  • Required GitHub checks pass on merge head 185e4ac1e
  • Merge conflict with current main resolved
  • Independent human review / account-owner sign-off required by ⚠️ Notice: 请勿提交低质量或“刷量”性质的 Pull Request #2485 (not established by the automated approval)
  • Ready for review (GitHub draft=false)

@CLAassistant

CLAassistant commented Sep 26, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.48148% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
.../harness/agent/middleware/AsyncToolMiddleware.java 81.48% 3 Missing and 2 partials ⚠️

📢 Thoughts on this report? Let us know!

@oss-maintainer

Copy link
Copy Markdown
Collaborator

CLA Not Signed

The Contributor License Agreement (CLA) check is currently pending on this PR (license/cla: Contributor License Agreement is not signed yet.). This PR cannot be merged until the CLA is signed.

@breezeFur please sign the CLA via the CLA assistant badge in the comment above, or visit https://cla-assistant.io/agentscope-ai/agentscope-java. Once signed, the license/cla status will turn green.


Automated check by github-manager-bot

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

First review of this PR. The diagnosis is correct and the fix is placed at the right boundary: AsyncToolMiddleware subscribes next.apply(input) inside Flux.create via a bare .subscribe(), which detaches from the caller chain and drops the Reactor Context, so AgentEventEmitter.fromContext(...) inside a tool has nothing to resolve. contextWrite(context -> context.putAll(sink.contextView())) is also exactly the idiom already used for the same problem elsewhere in this codebase (StaticLongTermMemoryHook.java:237), and runToolBatch in ReActAgent carries a comment describing the same failure mode for AgentSpawnTool — so this brings the acting middleware in line with existing practice rather than inventing a new mechanism. Read the code with the red/green evidence in the description and both new tests, and the per-subscription isolation claim holds.

Findings

  • [Warning] AsyncToolMiddleware.java:101-104 — the new DEBUG message is the only non-ASCII log string in src/main of agentscope-core/agentscope-harness; every neighbouring message is English. Its arguments are also evaluated on every subscription regardless of level.
  • [Warning] AsyncToolMiddleware.java:111 — putAll copies the entire caller context into a subscription that can outlive the foreground stream (the offload path completes the sink while the tool keeps running with a live emitter handle). Needs a sentence confirming the post-offload delivery contract, since deliverBackgroundResult also pushes the same result via the inbox.
  • [Info] AsyncToolMiddlewareTest.java:131 — the offload test decides on a 50 ms wall-clock race; StepVerifier.withVirtualTime or an injected Scheduler would make it deterministic.
  • [Info] AsyncToolMiddlewareTest.java:147 — the error channel of the detached subscription (asyncToolRegistry.fail(...), which itself does not inherit the context) is untested.

Two of these are questions about intent rather than defects, so I have not requested changes.

CI: all green on d76faa9e (build (ubuntu-latest), build (windows-latest), Check License, Check Module Sync, codecov/patch).

Cannot approve yet: license/cla is pending ("Contributor License Agreement is not signed yet."), so per this repo's contribution process the PR cannot be merged regardless of review outcome. @breezeFur please sign the CLA via the CLA assistant badge in the comment above — the code side looks close to ready.

Thanks for the thorough PR description, the explicit "red first" reproduction, and for scoping this to the remaining context-propagation gap in #2681 instead of the whole issue. That made the review much easier.


Automated review by github-manager-bot

@breezeFur
breezeFur marked this pull request as ready for review September 28, 2026 02:07
@breezeFur

Copy link
Copy Markdown
Author

Review follow-up is complete in 8482945. All four review threads have individual replies. Local Windows validation: 83 related regression tests passed, Spotless reactor check passed, the 6 focused tests passed on both JDK 21 and JDK 17, and the 3 virtual-time background cases passed in 5 consecutive runs. For this exact commit, GitHub now reports SUCCESS for Ubuntu/Windows builds, codecov/patch, license, module sync, and license/cla. The PR has been marked Ready for review. Review threads remain open for maintainer confirmation; no merge or protection bypass was performed.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Re-review of 84829453. All four points from the previous round are properly addressed — the diagnostic is now English and isDebugEnabled()-guarded (with the contextView read hoisted out of the argument position, so nothing is materialised when DEBUG is off), the detached messageBus/asyncToolRegistry subscribes now go through one subscribeWithContext(...) helper that forwards the parent context (this is exactly the recurrence I was worried about, and covering register/complete/fail/inboxPush/enqueueWakeup in one place is the right shape), the wall-clock race in the offload test is replaced by StepVerifier.withVirtualTime, and the error channel is now pinned by a parameterised test that also asserts the original message survives. The context-propagation fix itself is unchanged and correct, and the two Info notes below are follow-ups, not blockers.

license/cla is signed and CI on this head is green (build ubuntu-latest, build windows-latest, Check License, Check Module Sync, codecov/patch), which also clears the previous flakiness concern on the Windows job.

LGTM.

Note on the delivery semantics

I read the new comment beside putAll(callerContext) and accept the reasoning for keeping the emitter identity as-is in this PR — silently re-routing post-offload events would be a wider behavioural change than a context fix should carry. My only ask is that the at-least-once question gets tracked outside the comment (inline note below), because the test now asserts the behaviour rather than merely documenting it.

Author checklist

Heads-up on the PR description rather than the code: it still says the PR is kept Draft and that the account owner has not signed off, but the PR is currently marked ready for review on GitHub. Worth reconciling the two before a maintainer picks this up, since my approval is only a code-level signal and not the independent human sign-off #2485 asks for.


Automated review by github-manager-bot

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of ca6b591 (previous approval was on 8482945)

The follow-up refactor threads the captured callerContext into emitPlaceholderAndComplete(...) instead of re-reading the subscriber context off the FluxSink. That is behaviour-preserving inside Flux.create (sink.contextView() and the captured context are the same view), and it removes the last place where the async path depended on the sink being alive.

Verified against the sources: AgentEventEmitter.fromContext / fromForwardingContext, MessageBus.inboxPush / enqueueWakeup and the AsyncToolRegistry signatures all match what the commit uses, and the existing tests still cover the downstream, background-completion and background-failure context paths. No correctness, compatibility or performance concerns.

LGTM.


Automated review by github-manager-bot

@breezeFur

Copy link
Copy Markdown
Author

Synchronized the branch with current main at 9cfeaad4b and resolved the conflict in AsyncToolMiddleware while preserving both the Reactor Context forwarding and upstream's SUPPRESS_COMPLETION_CALLBACK / subagent completion behavior. Latest head: 185e4ac1eb5c440f5b7bf69eb5b58ecac3cf5f12.

Validation on this head:

  • 197 related regression tests passed (0 failures, 0 errors, 0 skipped).
  • Reactor Spotless checks and git diff --check passed.
  • CI run 46784999432: Ubuntu build, Windows build, Check License, Check Module Sync, and CLA all passed.
  • GitHub reports MERGEABLE / CLEAN; all six review threads remain resolved and there are no new review comments.

The prior automated approval was on ca6b5913; the conflict resolution preserves the PR's two-file diff against main, but maintainer re-confirmation on the merge head would be appreciated before squash merge. I cannot perform the merge because this account has read-only access to the upstream repository.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 紧急不重要

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]:agentscope.agent.event.emitter 和 AsyncToolMiddleware

4 participants